<?php
include_once ("mysqllib.php");
session_start();
ob_start();
//connect to the database
$db = new mysqllib();

// username and password sent from form
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$checkpassword = $_POST['checkpassword'];
// To protect MySQL injection 
$newusername = stripslashes($newusername);
$newpassword = stripslashes($newpassword);
$checkpassword = stripslashes($checkpassword);
$newusername = mysql_real_escape_string($newusername);
$newpassword = mysql_real_escape_string($newpassword);
$checkpassword = mysql_real_escape_string($checkpassword);

//if the passwords check
if ($newpassword == $checkpassword) {
	$query = "SELECT userName FROM User WHERE userName='$newusername'";
	$result = mysql_query($query);
	$count = mysql_num_rows($result);
	//If the username is not used
	if ($count == 0) {
		//encrypt the password for more security
		$encrypted_mypassword = md5($newpassword);
		//Insert the new user
		$query = "INSERT INTO User (userName, password, type) VALUES ('$newusername', '$encrypted_mypassword', 1)";
		$result = mysql_query($query);
		//if the insertion worked
		if ($result) {
			$query = "SELECT idUser FROM User WHERE userName='$newusername' AND password='$encrypted_mypassword'";
			$result = mysql_query($query);
			$data = mysql_fetch_array($result);
			// Register variables in SESSION and redirect
			$_SESSION['idUser'] = $data['idUser'];
			$_SESSIOn['status'] = $data['type'];
			$_SESSION["username"] = $newusername;
			$_SESSION["password"] = $encrypted_mypassword;
			header("location:index.php?page=videoList");
		}else{
			//fail insertion
			header("location:index.php?page=signup&action=fail");
		}
	}else{
		//username already used
			header("location:index.php?page=signup&action=name");
	}
}	else{
	//passwords are not the same
	 header("location:index.php?page=signup&action=pass");
}
ob_end_flush();
?>